<template>
  <div class="storage-wrapper">
    <div class="block-header">
      <n-space>
        <div class="title">{{ $t("file_list") }}</div>
      </n-space>
      <n-space style="margin-left: auto">
        <n-button
          @click="handleFileList"
          size="small"
          type="tertiary"
          secondary
          strong
        >
          <template #icon>
            <n-icon :size="14"> <Refresh></Refresh> </n-icon>
          </template>
          {{ $t("refresh") }}</n-button
        >
        <n-button
          @click="newFolderRef.open()"
          size="small"
          type="tertiary"
          secondary
          strong
        >
          <template #icon>
            <n-icon :size="14"> <FolderOutline></FolderOutline> </n-icon>
          </template>
          {{ $t("new_folder") }}</n-button
        >
        <n-button size="small" type="tertiary" secondary strong>
          <template #icon>
            <n-icon :size="14">
              <CloudDownloadOutline></CloudDownloadOutline>
            </n-icon>
          </template>
          下载</n-button
        >
        <n-button
          @click="handleOpenUploadPanel"
          size="small"
          type="primary"
          secondary
          strong
          >{{ $t("upload file") }}</n-button
        >
      </n-space>
    </div>
    <div class="useage-wrapper">
      <n-icon size="18">
        <SaveOutline></SaveOutline>
      </n-icon>
      <n-progress
        class="progress"
        status="success"
        type="line"
        :percentage="
          (currentInfo.fileSize / userStore.userInfo.storageSize) * 100
        "
        :show-indicator="false"
        :border-radius="1"
      />
      <n-space align="center">
        <span>已使用: {{ convertSize(currentInfo.fileSize) }}</span>
        /
        <span>总共:{{ convertSize(userStore.userInfo.storageSize) }}</span>
        <n-button size="small" type="warning" @click="Expand">
          <template #icon>
            <n-icon :size="14">
              <RocketOutline></RocketOutline>
            </n-icon>
          </template>
          扩展容量</n-button
        >
      </n-space>
    </div>
    <div class="file-path-wrapper">
      <n-space>
        <n-breadcrumb>
          <n-breadcrumb-item
            @click="handleFolderIndex(index)"
            v-for="(item, index) in filePathList"
            >{{ item.label }}</n-breadcrumb-item
          >
        </n-breadcrumb>
      </n-space>
      <n-space>
        <n-input
          style="width: 150px"
          size="small"
          :placeholder="$t('please input keyword')"
        >
          <template #prefix>
            <n-icon :component="SearchOutline" />
          </template>
        </n-input>
      </n-space>
    </div>
    <div class="table-wrapper">
      <n-data-table
        @update:checked-row-keys="handleCheck"
        :bordered="false"
        :columns="dataColumn"
        :data="fileList"
        :rowKey="rowKey"
        style="height: 600px"
      />
    </div>
    <DialogFormBuilder
      :schema="newFolderSchema"
      @submit="handleNewFolder"
      ref="newFolderRef"
    ></DialogFormBuilder>
    <DialogFormBuilder
      :schema="editFolderSchema"
      @submit="handleEditFolder"
      ref="editFolderRef"
    ></DialogFormBuilder>
    <uploadPanel :path="path" ref="uploadPanelRef"></uploadPanel>

    <extend v-model="showModal" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, h, computed } from "vue";
import extend from "../../../../components/extend/extend.vue";
// import { useRouter } from "vue-router";
import {
  SearchOutline,
  EllipsisVerticalOutline,
  Refresh,
  FolderOutline,
  CloudDownloadOutline,
  SaveOutline,
  RocketOutline,
  FolderOpenOutline,
  DocumentOutline,
} from "@vicons/ionicons5";
import { DataTableRowKey, NButton, NIcon, NSpace } from "naive-ui";
import { RowData } from "naive-ui/es/data-table/src/interface";
import newFolderSchema from "../form/new-folder.json";
import editFolderSchema from "../form/edit-folder.json";
import DialogFormBuilder from "@/components/form-builder/dialog.vue";
import uploadPanel from "./upload-panel.vue";
import { useRouter } from "vue-router";
import {
  uplpadFile,
  getFileList,
  recusiveDelete,
  editFile,
  getCurrentSize,
} from "@/api";
import { v1 } from "uuid";
import { useMessage } from "naive-ui";
import { useDialog } from "naive-ui";
import { convertSize } from "@/utils";
import { useUserStore } from "@/store/user";
// const router = useRouter()

const showModal = ref(false); // 拓展容量弹窗
const userStore = useUserStore();
const dialog = useDialog();
const message = useMessage();
const newFolderRef = ref();
const editFolderRef = ref();
const uploadPanelRef = ref();
const router = useRouter();
const currentInfo = ref({
  fileSize: 0,
});
const filePathList = ref([{ label: "全部文件", value: "1" }]);
const path = computed(() => {
  return filePathList.value.map((item) => item.value).join("/");
});
const useageInfo = ref({
  total: 2 * 1024 * 1024 * 1024,
  useage: 1 * 1024 * 1024 * 1024,
});
const checkedRowKeysRef = ref([]);
const dataColumn = [
  {
    type: "selection",
  },
  {
    title: "名称",
    key: "name",
    render(row) {
      return h(
        NSpace,
        { align: "center", style: { lineHeight: "14px" } },
        {
          default: () => [
            h(
              NIcon,
              { size: 18 },
              {
                default: () => {
                  return h(
                    row.isFolder ? FolderOpenOutline : DocumentOutline,
                    {}
                  );
                },
              }
            ),
            h(
              NButton,
              {
                quaternary: true,
                type: "primary",
                onClick() {
                  if (row.isFolder) {
                    handleFolderDetail(row.name, row.uid);
                  } else {
                    handleFileDetail(row.uid);
                  }
                },
              },
              { default: () => row.name || "--" }
            ),
          ],
        }
      );
    },
  },
  {
    title: "类型",
    key: "type",
    render(row) {
      return h("div", {}, { default: () => row.type || "--" });
    },
  },
  {
    title: "大小",
    key: "size",
    render(row) {
      return h("div", {}, { default: () => convertSize(row.size) || "--" });
    },
  },
  {
    title: "最后修改时间",
    key: "updateTime",
  },
  {
    title: "操作",
    key: "op",
    render(row) {
      return h(NSpace, { align: "center" }, [
        h(
          NButton,
          {
            type: "primary",
            stronger: true,
            quaternary: true,
            onClick() {
              editFolderRef.value.open({ name: row.name, uid: row.uid });
            },
          },
          {
            default: () => "修改",
          }
        ),
        h(
          NButton,
          {
            type: "error",
            stronger: true,
            quaternary: true,
            onClick() {
              handleDelete(row.uid);
            },
          },
          {
            default: () => "删除",
          }
        ),
      ]);
    },
  },
];
const fileList = ref([
  {
    name: "测试文件",
    size: "14KB",
    updateTime: "2024-01-14: 12:34",
    uid: "",
  },
]);
const rowKey = (row: RowData) => {
  return row.uid;
};
const handleCheck = (rowKeys: DataTableRowKey[]) => {
  checkedRowKeysRef.value = rowKeys;
};
const handleNewFolder = (form: any) => {
  console.log(form);
  form["uid"] = v1();
  form["isFolder"] = true;
  form["status"] = 1;
  form["parentId"] = filePathList.value[filePathList.value.length - 1].value;
  uplpadFile(form)
    .then((res) => {
      message.success("添加成功");
      console.log(res);
    })
    .catch((e) => {
      message.error(`添加失败:${e}`);
    });
  // form[""]
};
const handleFileList = () => {
  const parentId = filePathList.value[filePathList.value.length - 1].value;
  getFileList({ page: 1, size: 20, parentId })
    .then((res: any) => {
      console.log(res);
      fileList.value = res.data.list;
      handleFileSize();
    })
    .catch((e) => {
      message.error(`获取数据失败:${e}`);
      console.log(e);
    });
};
const handleFolderDetail = (name: string, uid: string) => {
  filePathList.value.push({
    label: name,
    value: uid,
  });
  handleFileList();
};
const handleFileDetail = (uid: string) => {
  // router.push({ path: `/viewer?uid=${uid}` });
  window.open(`/editor/#/viewer?uid=${uid}`, "_blank");
};
const handleFolderIndex = (index: number) => {
  console.log(index, filePathList.value.length);
  if (index == filePathList.value.length - 1) {
    return;
  }
  filePathList.value.splice(index + 1, filePathList.value.length);
  handleFileList();
};
const handleDelete = (uid: string) => {
  dialog.error({
    title: "确定要删除?",
    content: "删除后将不可恢复",
    positiveText: "确定",
    negativeText: "不确定",
    onPositiveClick: () => {
      recusiveDelete({ uid })
        .then((res) => {
          message.success("删除成功");
          handleFileList();
        })
        .catch((e) => {
          message.error("删除失败");
        });
    },
  });
};
const handleEditFolder = (data: any) => {
  console.log(data);
  editFile(data)
    .then((res) => {
      message.success("修改成功");
    })
    .catch((e) => {
      message.error(`修改失败:${e}`);
    });
};
const handleOpenUploadPanel = () => {
  uploadPanelRef.value.open();
};
const handleFileSize = () => {
  getCurrentSize().then((res: any) => {
    console.log(res);
    currentInfo.value = res.data;
  });
};

// 点击扩展容量
const Expand = () => {
  // console.log('点击扩展容量');
  // router.push('/expand')
  showModal.value = true;
};
onMounted(() => {
  handleFileList();
});
</script>

<style lang="scss" scoped>
.storage-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.block-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title {
    font-weight: bold;
    font-size: 24px;
  }
}
.useage-wrapper {
  margin: 24px 0;
  display: flex;
  align-items: center;
  .progress {
    // width: 500px;
    flex: 1;
    margin: 0 8px;
  }
}
.file-path-wrapper {
  margin: 12px 0;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.table-wrapper {
  flex: 1;
  overflow-y: scroll;
}
::-webkit-scrollbar {
  display: none;
}
</style>
